package com.luzhikun.listener;

import com.luzhikun.db.JDBCUtil;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/*
 * @Author liu-miss
 * @Description 在应用启动时创建线程池，加快程序速度
 * @Date 8:42 2021/5/8
 * @Param
 * @return
 **/
@WebListener
public class LoginListener implements ServletContextListener {


    @Override
    public void contextInitialized(ServletContextEvent sce) {
        // 获取全局作用域对象
        ServletContext sc = sce.getServletContext();
        // 创建JDBCUtil对象
        JDBCUtil jdbcUtil=new JDBCUtil();
        // 创建一个Map集合
        Map map=new HashMap();
        // 创建连接池
        for (int i = 0; i < 20; i++) {
            try {
                // 获取20次连接
                Connection connection = jdbcUtil.getConnection();
                System.out.println("老子出生了");
                // true代表空闲，false代表占用
                map.put(connection,true);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        // 将这个map放入全局作用域对象中
        sc.setAttribute("conn",map);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        ServletContext sc = sce.getServletContext();
        Map conn = (Map) sc.getAttribute("conn");
        Set set = conn.keySet();
        Iterator iterator = set.iterator();
        while (iterator.hasNext()){
            Connection connection= (Connection) iterator.next();
            if (connection!=null){
                try {
                    connection.close();
                    System.out.println("吴杰是狗");
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }

        }
    }


}
